/**
 * @see 这个组件接受两个参数,type和show，根据不同的类型显示不同的文字
 * @param {type} String (loading none err)
 * @param {show} Boolean
 * @param {top} String
 * @param {delay} Number 延迟显示加载效果的时间（防止闪烁）
 */
const app = getApp()
let times = null
Component({
  options: {
    addGlobalClass: true
  },
  properties: {
    type: { // loading none err
      type: String,
      value: 'loading',
      observer: function (type) {
        this.centerDispatch()
      }
    },
    delay: {
      type: Number,
      value: 200
    },
    top: {
      type: String,
      value: '60%'
    },
    show: {
      type: Boolean,
      value: false,
      observer: function (show) {
        this.centerDispatch()
      }
    }
  },
  // observers: {
  //   'type, show': function (type, show) {
  //   }
  // },
  data: {
    content: '页面加载失败，请重试',
    spinning: false,
    imgUrl: '../../assets/images/loading.png',
    showButton: app.globalData.isConnected,
  },
  methods: {
    centerDispatch () {
      const { show, type } = this.data
      if (!show) {
        this.setData({
          spinning: show
        })
      }
      clearTimeout(times)
      times = setTimeout(() => {
        switch (type) {
          case 'loading':
            this.setData({
              content: '拼命加载中...',
              imgUrl: '../../assets/images/loading.png',
              showButton: false,
              spinning: show
            })
            break
          case 'none':
            this.setData({
              content: '暂无数据',
              imgUrl: '../../assets/images/none.png',
              showButton: false,
              spinning: show
            })
            break
          case 'err':
            const { isConnected } = app.globalData
            if (isConnected) {
              this.setData({
                content: '页面加载失败，请重试',
                imgUrl: '../../assets/images/fail.png',
                showButton: isConnected,
                spinning: show
              })
            } else {
              this.setData({
                content: '似乎已断开与互联网的链接~',
                imgUrl: '../../assets/images/err.png',
                showButton: isConnected,
                spinning: show
              })
            }
            break
          default:
            this.setData({
              content: '',
              imgUrl: '',
              showButton: false,
              spinning: false
            })
        }
      }, this.data.delay)
    },
    click () {
      this.triggerEvent('click')
    }
  }
});
